package com.jc.service.api.yx163.order;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jc.cds.model.CustomXorder;
import com.jc.common.util.DateTimeUtil;
import com.jc.common.util.JcStringUtil;
import com.jc.common.util.UUIDUtil;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.OrderProducts;
import com.jc.ds.model.Xorder;
import com.jc.ds.model.XorderMarge;
import com.jc.framework.enums.Booleans;
import com.jc.framework.enums.LogType;
import com.jc.framework.enums.OrderMargeType;
import com.jc.framework.enums.OrderStatus;
import com.jc.framework.enums.SystemUser;
import com.jc.framework.enums.YanXuanServiceName;
import com.jc.service.api.yx163.YanXuanAdapter;
import com.jc.service.model.yx.Order;
import com.jc.service.model.yx.OrderSku;
import com.jc.service.model.yx.YanXuanResult;
import com.jc.service.order.XorderService;
import com.jc.service.orderproduct.OrderProductsService;
import com.jc.service.xordermarge.XorderMargeService;
import com.jc.service.xorderprocess.XorderProcessService;

@Service
public class YanXuanOrderServiceImpl extends YanXuanAdapter implements YanXuanOrderService {

	@Autowired
	OrderProductsService orderProductsService;
	
	@Autowired
	XorderMargeService xorderMargeService;
	
	@Autowired
	XorderProcessService xorderProcessService;
	
	@Autowired
	XorderService xorderService;
	
	@Transactional
	public void pushOrder(CustomXorder order) {
		Order pushOrder = packageOrder(order);
		String orderJsonString = JSONObject.toJSONString(pushOrder);
		LinkedHashMap<String, Object> paramMap = new LinkedHashMap<String, Object>();
		paramMap.put("method", YanXuanServiceName.YX_CHANNEL_ORDER.getName());
		paramMap.put("order", orderJsonString);
		paramMap.put("logType", LogType.PUSH_163_ORDER);//用于记录日志
		
		LinkedHashMap<String, Object> _params = getSign(paramMap);
		
		YanXuanResult result = postYanXuan(_params);
		if(result == null || !StringUtils.equals("200", result.getCode())) {
			//向网易严选推送订单失败
			xorderProcessService.addXorderProcess(order.getChannelOrderId(), "订单向网易严选推送失败,失败原因: " + result.getMessage() , SystemUser.ADMIN.getDesc(), order.getId());
			Xorder updateOrder = new Xorder();
			updateOrder.setUpdateTime(new Date());
			updateOrder.setId(order.getId());
			updateOrder.setOrderStatus(OrderStatus.push_final.getName());
			xorderService.modify(updateOrder, false);
		}else {
			xorderProcessService.addXorderProcess(order.getChannelOrderId(), "订单向网易严选推送成功", SystemUser.ADMIN.getDesc(), order.getId());
			Xorder updateOrder = new Xorder();
			updateOrder.setId(order.getId());
			updateOrder.setUpdateTime(new Date());
			updateOrder.setOrderStatus(OrderStatus.push_ok.getName());
			xorderService.modify(updateOrder, false);
			
			//记录订单产品的packageId
			List<Object> resultList = (List<Object>)result.getResult();
			
			for(Object obj : resultList) {
				
				if(JcStringUtil.isJSONValid(obj.toString())) {
					JSONObject retObject = JSONObject.parseObject(obj.toString());
					JSONArray orderPackages = retObject.getJSONArray("orderPackages");
					for(int i = 0 ; orderPackages != null && i < orderPackages.size() ; i++) {
						JSONObject orderPackage = orderPackages.getJSONObject(i);
						String packageId = orderPackage.getString("packageId");
						JSONArray skuArrayObject = orderPackage.getJSONArray("orderSkus");
						
						//更新每一行的packageId,申请售后的时候需要用到
						
						for(int k  = 0 ; CollectionUtils.isNotEmpty(skuArrayObject) && k < skuArrayObject.size() ; k++) {
							JSONObject skuObject = skuArrayObject.getJSONObject(k);
							OrderProducts orderProduct = new OrderProducts();
							orderProduct.setSupplierSkuId(skuObject.getString("skuId"));
							orderProduct.setOrderId(order.getId());
							orderProduct.setIsGift(Booleans.FALSE.getName());
							orderProduct.setIsBind(0);
							orderProduct.setSubGoods(1);
							orderProduct.setIsDelete(Booleans.FALSE.getName());
							
							List<OrderProducts> plist = orderProductsService.queryAll(orderProduct);
							for(OrderProducts p : plist) {
								p.setSupplierReturnId(packageId);
								orderProductsService.modify(p, false);
							}
							
						}
						
						
					}
					
				}
				
			}
			
			
			
			
			
		}
	}
	
	public YanXuanResult regYanXuanApiCallBack() {
		LinkedHashMap<String, Object> paramMap = new LinkedHashMap<String, Object>();
		paramMap.put("method", YanXuanServiceName.YANXUAN_CALLBACK_METHOD_REGISTER.getName());
		paramMap.put("logType", LogType.YANXUAN_CALLBACK_METHOD_REGISTER);//用于记录日志
		Set<String> serviceSet = new HashSet<String>();
		serviceSet.add(YanXuanServiceName.YANXUAN_CALLBACK_ORDER_CANCEL.getName());
		serviceSet.add(YanXuanServiceName.YANXUAN_NOTIFICATION_INVENTORY_COUNT_CHECK.getName());
		serviceSet.add(YanXuanServiceName.YANXUAN_NOTIFICATION_ORDER_DELIVERED.getName());
		serviceSet.add(YanXuanServiceName.YANXUAN_NOTIFICATION_ORDER_EXCEPTIONAL.getName());
		serviceSet.add(YanXuanServiceName.YANXUAN_NOTIFICATION_ORDER_REFUND_ADDRESS.getName());
		serviceSet.add(YanXuanServiceName.YANXUAN_CALLBACK_ITEM_CHANGE.getName());
		//严选拒绝退货
		serviceSet.add(YanXuanServiceName.YANXUAN_ORDER_REFUND_REJECT.getName());
		//退货包裹确认收货
		serviceSet.add(YanXuanServiceName.YANXUAN_RETURN_CONFIRMATION_RECEIPT.getName());
		//取消退货
		serviceSet.add(YanXuanServiceName.SYSTEM_CANCELS_RETURN.getName());
		paramMap.put("methods", StringUtils.join(serviceSet, ","));
		LinkedHashMap<String, Object> _params = getSign(paramMap);
		return postYanXuan(_params);
	}
	
	
	public YanXuanResult regYanXuanApiProductCallBackField() {
		LinkedHashMap<String, Object> paramMap = new LinkedHashMap<String, Object>();
		paramMap.put("method", YanXuanServiceName.YANXUAN_CALLBACK_ITEMCHANGE_REGISTER.getName());
		paramMap.put("logType", LogType.YANXUAN_CALLBACK_ITEMCHANGE_REGISTER);//用于记录日志
		
		Set<String> fields = new HashSet<String>();
		fields.add("item.skuList.channelSkuDetail.channelPrice");
		//fields.add();
		paramMap.put("fields", StringUtils.join(fields, ","));
		LinkedHashMap<String, Object> _params = getSign(paramMap);
		return postYanXuan(_params);
	}
	
	
	
	public YanXuanResult exeCallBack(String channelOrderId) {
		
		LinkedHashMap<String,Object> param = new LinkedHashMap<String,Object>();
		param.put("method", "/callbackAuditCancelOrder");
		param.put("orderId",channelOrderId);
		param.put("cancel",true);
		param.put("logType",LogType.YANXUAN_CALLBACK_METHOD_REGISTER);
		param.put("url","http://openapi-test.you.163.com/mock/api/v1/callbackAuditCancelOrder");
		LinkedHashMap<String, Object> _params = getSign(param);
		return postYanXuan(_params);
	}
	
	
	
	public YanXuanResult exeExpressCallBack(String channelOrderId) {
		
		LinkedHashMap<String,Object> param = new LinkedHashMap<String,Object>();
		param.put("method", "/callbackDeliveryOrder");
		param.put("orderId",channelOrderId);
		param.put("logType",LogType.YANXUAN_CALLBACK_METHOD_REGISTER);
		param.put("url","http://openapi-test.you.163.com/mock/api/v1/callbackDeliveryOrder");
		LinkedHashMap<String, Object> _params = getSign(param);
		return postYanXuan(_params);
	}


	
	@Transactional
	public YanXuanResult canelOrderByYanXuan(String orderId) {
		String channelOrderId = null;
		Xorder order = xorderService.queryById(Long.valueOf(orderId));
		if(order == null) throw new BaseServiceException("取消订单错误,订单不存在"); 
		XorderMarge marge = xorderMargeService.getXorderMarge(Long.valueOf(orderId));
		if(marge != null) {
			channelOrderId = marge.getNewChannelOrderId();
		}else {
			channelOrderId   = order.getChannelOrderId();
		}
		LinkedHashMap<String, Object> paramMap = new LinkedHashMap<String, Object>();
		paramMap.put("method", YanXuanServiceName.YANXUAN_ORDER_PAID_CANCEL.getName());
		paramMap.put("orderId",channelOrderId);
		paramMap.put("logType", LogType.YANXUAN_ORDER_PAID_CANCEL);//用于记录日志
		LinkedHashMap<String, Object> _params = getSign(paramMap);
		YanXuanResult ret = postYanXuan(_params);
		if (ret != null && StringUtils.equals("200", ret.getCode())) {
			// 作废当前的临时订单号
			if(marge != null) {
				marge.setIsDelete(Booleans.TRUE.getName());
				xorderMargeService.modify(marge, false);
			}
			//取消订单成功后需要设置订单状态为 : 待人工审核
			order.setOrderStatus(OrderStatus.wait_auditing.getName());
			xorderService.modify(order, false);
	    	//同时需要生成一条临时订单号,用于下一次推送
			XorderMarge newXorderMarge = new XorderMarge();
			newXorderMarge.setChannelOrderId(order.getChannelOrderId());
			newXorderMarge.setCreateTime(new Date());
			newXorderMarge.setIsDelete(Booleans.FALSE.getName());
			newXorderMarge.setNewChannelOrderId(UUIDUtil.getUUID());
			newXorderMarge.setOrderId(order.getId());
			newXorderMarge.setType(OrderMargeType.ORDER_ID_FLUSH.getName());
			xorderMargeService.add(newXorderMarge, false);
        }
		
		return ret;
	}
	
	
	
	
	public Order packageOrder(CustomXorder order) {
		if(order == null) return null;
		List<OrderSku> skuList = new ArrayList<OrderSku>();
		Order o = new Order();
		String _oms_channel_order_id = order.getChannelOrderId();
		XorderMarge marge = xorderMargeService.getXorderMarge(order.getId());
		if(marge != null) {
			_oms_channel_order_id = marge.getNewChannelOrderId();
		}
		o.setOrderId(_oms_channel_order_id);
		o.setSubmitTime(DateTimeUtil.getDate(order.getChannelCreateTime(),DateTimeUtil.LONG_TIME_FORMAT));
		o.setPayTime(DateTimeUtil.getDate(order.getPayTime()));
		o.setReceiverName(order.getConsigneeName());
		o.setReceiverMobile(order.getConsigneeMobile());
		o.setReceiverPhone(order.getConsigneeMobile());
		o.setReceiverProvinceName(order.getConsigneeProvinceName());
		o.setReceiverCityName(order.getConsigneeCityName());
		o.setReceiverDistrictName(order.getConsigneeRegionName());
		o.setReceiverAddressDetail(order.getConsigneeAddress());
		o.setRealPrice(order.getPaidAmount());
		o.setExpFee(BigDecimal.ZERO);
		o.setPayMethod("ALIPAY");
		List<OrderProducts> productList = orderProductsService.queryProductByOrderId(order.getId());
		
		for(OrderProducts prod : productList) {
			OrderSku sku = new OrderSku();
			sku.setActivityTotalAmount(BigDecimal.ZERO);
			sku.setCouponTotalAmount(BigDecimal.ZERO);
			sku.setOriginPrice(prod.getNormalPrice());
			sku.setProductName(prod.getProductName());
			sku.setSaleCount(prod.getProductNums());
			sku.setSkuId(prod.getSupplierProductId());
			sku.setSubtotalAmount(prod.getTotalAmount());
			skuList.add(sku);
		}
		
		if(CollectionUtils.isEmpty(skuList)) {
			throw new BaseServiceException("组装网易严选订单错误, 缺少订单明细行信息 ! ");
		}else {
			o.setOrderSkus(skuList);
			return o;
		}
	}
	
	
	
	
	
	
	
	
	
	
	
}
